<template>

    <div>
         
        <div class="content-header">
        
            <div class="container-fluid">

          </div>
        </div>
 
        <div class="content">
          <div class="container-fluid">


            <div class="row">
              <div class="col-lg-3">
                <el-tree ref="treeRef" :indent="30" class="filter-tree" :data="data" :props="defaultProps" default-expand-all
                        :filter-node-method="filterNode" @node-click="handleNodeClick"></el-tree>
              </div>
              <div class="col-lg-7 ml-2">

                  <pdf-viewer v-if="isPdf" :src="pdfUrl"></pdf-viewer>
                  <!-- <pdf  :src="pdfSrc" ></pdf> -->

                  <div  v-html="staticHtml"></div>
              
                </div>

            </div>
        
          </div>


        </div>
        
      </div>

 
</template>

<script>
import PdfViewer from '../PdfViewer.vue';
import { getWithNginx } from '@/utils/api'; //get, 
import { ref } from 'vue';
import gconfig from '@/config/global_config'
import { getTreeView,getFileContent } from "@/apis/chapter";
//import { pdf } from 'vue3-pdfjs'

//import axios from 'axios';

const fixImgSrc = (html) => {
    return html.replace(/data-savepage-src/g, 'src');
};

// const removeBaseTag = (html) => {
//     const parser = new DOMParser();
//     const doc = parser.parseFromString(html, 'text/html');
//     const baseTag = doc.querySelector('base');
//     if (baseTag) {
//         baseTag.remove();
//     }
//     return doc.body.innerHTML;
// };

export default {
    name: "bookChapterIndex",
    data() {
        return {
            staticHtml: '',
            book_id: null,
            isPdf: false,
            pdfSrc: 'http://localhost:81/static/chapters/java灵魂15问.pdf',
            data: [
                
            ],
            defaultProps: {
                children: "children",
                label: "title",
            },
            startRenderTime: 0,
            endRenderTime: 0,            
        };
    },
    mounted() {
        this.book_id = this.$route.query.book_id;
         console.log('Book ID:', this.book_id);
         this.startRenderTime = Date.now(); // 开始时间
        this.getAll();
    },
    methods: {
    
        handleNodeClick(nodeData, node) {
            console.log(node);
            if (!nodeData.children) {
                //this.$router.push(nodeData.url);
             this.loadContent(nodeData.url);
            }
        },
        
         async loadStaticHtml(url) {
            // 通过springboot的资源映射获取资源，速度太慢了，具体原因不清楚，但是通过接口获取资源速度很快，大概快几百倍 13秒->1秒内
            try {
                this.startRenderTime = Date.now();
                console.log("beg" + this.startRenderTime)
                const response = await getWithNginx(url);
                this.staticHtml = fixImgSrc(response);
                //this.staticHtml = removeBaseTag(response);
                //this.staticHtml = response;
                //console.log()
            } catch (error) {
                console.error('An error occurred while loading the static HTML:', error);
            }
            this.$nextTick(() => {
                this.endRenderTime = Date.now(); // DOM更新完成的时间
                console.log("end" + this.endRenderTime)
                console.log(`Total render time: ` + (this.endRenderTime - this.startRenderTime));
            });
        },
        async loadStaticHtmlV2(url) {
            const response = await getFileContent(url);
            console.log(response); // 检查整个响应对象
             // 如果响应是一个blob (文件对象)，我们需要将其转换为文本
        if (response.data instanceof Blob) {
            // 使用FileReader将Blob转换为文本
            const reader = new FileReader();
            reader.onload = (e) => {
                console.log("is blob")
                this.staticHtml = fixImgSrc(e.target.result);
            };
            reader.onerror = (e) => {
                console.error('FileReader error', e);
            };
            reader.readAsText(response.data); // 读取Blob为文本
        } else {
            // 假设response已经是文本格式
            this.staticHtml = fixImgSrc(response.data);
        }
            //this.staticHtml = fixImgSrc(response);
        },
         async loadContent(url) {
            // 判断 URL 是否为 PDF 后缀
            if (url.toLowerCase().endsWith('.pdf')) {
                this.isPdf = true;
                await this.loadPdf(url);
            } else {
                this.isPdf = false;
                // 加载静态 HTML
                this.loadStaticHtmlV2(url);
                //this.loadStaticHtml(url);
            }
        },
       async getAll() {
            // 发送异步请求

            getTreeView(this.book_id).then((res) => {
                if (res) {
                    this.data = res
                    this.loadContent(this.data[0].children[0].url);
                }
            }).catch((error) => {
                console.log('Failed with reason:', error); // 输出: Failed with reason: error
            });

            // var url = '/chapter/get_tree_view'
            // try {
            //     // 发送 application/json 类型的 POST 请求
            //     var retData = await get(url, { book_id: this.book_id }, 'form');
            //     this.data = retData.data
            //     this.loadContent(this.data[0].children[0].url);
            //     // 发送 application/x-www-form-urlencoded 类型的 POST 请求 (取消注释以使用)
            //     // this.result = await post(url, data, 'form');
            // } catch (error) {
            //     console.error('请求失败:', error);
            // }

        },
    },
     created() {
        //this.getAll();
    },
    components: {
         PdfViewer
    },
     setup() {
        const pdfUrl = ref(''); // 您从响应中获得的 PDF URL 或 Blob URL
        async function loadPdf(url) {
            // 老逻辑如下
            //pdfUrl.value = gconfig.constants.API_NGINX_ORIGIN + url; 

            //console.log('1111', gconfig.constants.API_NGINX_ORIGIN + url)
            
            pdfUrl.value = gconfig.constants.API_ORIGIN + "/chapter/get_file_content?path=" + encodeURIComponent(url);
           
        }
        // 在适当的生命周期挂钩中调用 'loadPdf' 方法，或在需要时调用。
        return {
            pdfUrl,
            loadPdf
        };
    }
};
</script>
<style scoped>
.filter-tree {
    width: 320px;
    overflow: hidden;
}


::v-deep .el-tree-node__content {
  min-height: 45px; /* Adjust the node height to your preference */
  display: flex;
  align-items: center;
  white-space: normal;
  line-height: normal;
  word-wrap: break-word;
  /* margin-left: -20px; */
}

</style>